package com.sxkf.template.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxkf.core.api.vo.R;
import com.sxkf.core.third.sms.ALISMSUtils;
import com.sxkf.template.entity.Post;
import com.sxkf.template.entity.User;
import com.sxkf.template.entity.UserCoupon;
import com.sxkf.template.service.PostService;
import com.sxkf.template.service.UserCouponService;
import com.sxkf.template.service.UserService;
import com.sxkf.template.vo.request.user.UserDetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.util.CheckEmptyUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张广成
 * @since 2024-10-31 10:01:47
 */
@Api(tags = "用户基本信息管理模块")
@RestController
@RequestMapping("/users")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserCouponService userCouponService;
    @Resource
    private PostService postService;


    //todo 邀请用户 ，生成邀请图，抽奖（逻辑需和客户确认），下级下单给上级反优惠券（逻辑需确认）
    // FINISH：我的评价，修改登录密码，注销，收藏，我的拼团查看，足迹，余额支付，

    @ApiOperation(value = "后台分页查询用户")
    @GetMapping(value = "/page")
    public R<IPage<User>> page(@RequestParam Integer pageNo,
                               @RequestParam Integer pageSize,
                               @RequestParam(required = false) String phone) {
        Page<User> page = userService.page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<User>()
                .like(CheckEmptyUtil.isNotEmpty(phone), User::getPhone, phone)
                .orderByDesc(User::getCreateTime));
        return R.success(page);
    }

    @ApiOperation("更新用户信息(注销用户也可用)")
    @PostMapping("/update")
    public R<Boolean> update(@RequestBody User user) {
        return R.success(userService.updateUser(user));
    }

    @ApiOperation("查询用户信息")
    @GetMapping("/getById")
    public R<User> getById(@RequestParam String id) {
        long count = userCouponService.count(new LambdaQueryWrapper<UserCoupon>()
                .eq(UserCoupon::getState, "ENABLE")
                .eq(UserCoupon::getUserId, id));
        User user = userService.getById(id);
        if (CheckEmptyUtil.isEmpty(user)) {
            throw new SxkfException("用户不存在");
        }
        user.setHongbao(count);

        List<Post> postList = postService.list(new LambdaQueryWrapper<Post>()
                .eq(Post::getUserId, id));
        Long likeCount = 0L;
        for (Post post : postList) {
            likeCount += post.getLikeCount();
        }
        user.setPostLikeCount(likeCount);

        return R.success(user);
    }

    @ApiOperation(value = "绑定邀请关系")
    @PostMapping(value = "/bind")
    public R<?> bind(@RequestParam String userId, @RequestParam String inviterId) {
        User user = userService.getById(userId);
        if (CheckEmptyUtil.isNotEmpty(user.getInviterId())) {
            throw new SxkfException("您已被他人邀请");
        }
        user.setInviterId(inviterId);
        userService.updateById(user);
        return R.success();
    }

    @ApiOperation(value = "查询自己邀请的用户")
    @GetMapping(value = "/pageSon")
    public R<IPage<User>> pageSon(@RequestParam Integer pageNo, @RequestParam Integer pageSize, @RequestParam String userId) {
        Page<User> page = userService.page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<User>().eq(User::getInviterId, userId).orderByDesc(User::getCreateTime));
        return R.success(page);
    }


//    @ApiOperation("修改登录密码")
//    @GetMapping("/updatePass")
//    public R<String> updatePass(@ApiParam("用户id")
//                                @RequestParam String id,
//                                @ApiParam("新密码")
//                                @RequestParam String oldPass,
//                                @ApiParam("新密码")
//                                @RequestParam String newPass){
//        User user = userService.getById(id);
//        if (user.getPassword().equals(oldPass)){
//            user.setPassword(newPass);
//            boolean update = userService.updateById(user);
//            if (update){
//                return R.success("修改成功");
//            }
//        }
//        return R.error("修改失败");
//    }

    @ApiOperation("发送验证码")
    @PostMapping("/getCaptcha")
    public R<String> getCaptcha(@RequestParam String phoneNumber) {
        userService.sendCaptcha(phoneNumber);
        return R.success();
    }

    @ApiOperation("修改登录密码")
    @GetMapping("/updatePass")
    public R<String> updatePass(@ApiParam("用户id")
                                @RequestParam String id,
                                @ApiParam("验证码(暂时不做校验)")
                                @RequestParam String captcha,
                                @ApiParam("新密码")
                                @RequestParam String newPass) {
        userService.updatePass(id, captcha, newPass);
        return R.success();

    }

    @ApiOperation(value = "检查验证码是否正确")
    @PostMapping(value = "/checkPhoneCode")
    public R<Boolean> checkPhoneCode(String phoneNumber, String code) {
        return R.success(userService.checkPhoneCode(phoneNumber, code));
    }

    @ApiOperation("修改手机号")
    @GetMapping("/updatePhone")
    public R<String> updatePhone(@ApiParam("用户id") @RequestParam String id,
                                 @ApiParam("验证码(暂时不做校验)") @RequestParam String captcha,
                                 @ApiParam("新电话号码") @RequestParam String newPhone) {
        userService.updatePhone(id, captcha, newPhone);
        return R.success();
    }

    @ApiOperation("用户实名认证")
    @PostMapping("/realNameUser")
    public R<Boolean> realNameUser(@RequestBody UserDetailVo userDetailVo) {
        return R.success(userService.realNameUser(userDetailVo));
    }

    @ApiOperation("用户注销")
    @GetMapping("/byebye")
    public R<Boolean> byebye(@RequestParam String userId, HttpServletRequest request) {
        return R.success(userService.byebye(userId, request));
    }

    @ApiOperation("附近的人")
    @GetMapping("/nearby")
    public R<IPage<User>> nearby(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
                                 @RequestParam Double longitude, @RequestParam Double latitude) {
        return R.success(userService.nearby(pageNo, pageSize, longitude, latitude));
    }

    @ApiOperation(value = "app启动时同步用户定位")
    @GetMapping(value = "/loadLocation")
    public R<?> loadLocation(@RequestParam String userId, @RequestParam Double longitude, @RequestParam Double latitude) {
        userService.loadLocation(userId, longitude, latitude);
        return R.success();
    }
}
